﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using UtilsLib.UtilsLog;

namespace UtilsLib.UtilsFile.XML
{
    public static class XMLReader
    {
      
        /// <summary>
        /// Get the content of each node [nodeName] in the xml file [pathXMLFile]
        /// </summary>
        /// <param name="pathXMLFile">The path to the XML file</param>
        /// <param name="nodeName"> The name of the node to extract</param>
        /// <returns></returns>
        public static List<string> GetNodeContentListByNodeName(string pathXMLFile, string nodeName)
        {
            XmlDocument xmlDoc = new XmlDocument();
            
            xmlDoc.Load(pathXMLFile);
            List<string> results = new List<string>();

            XmlNodeList urlLoc = xmlDoc.GetElementsByTagName(nodeName);

            foreach (XmlNode node in urlLoc)
            {
                results.Add(node.InnerXml);
            }

            return results;
        }

        /// <summary>
        /// Get the content of each node [nodeName] in the xml file [pathXMLFile] with an autoreplace of the content.
        /// </summary>
        /// <param name="pathXMLFile">The path to the XML file</param>
        /// <param name="nodeName">The name of the node to extract</param>
        /// <param name="valueToReplace">The string to replace in the content</param>
        /// <param name="value">The value wich will replace the [valueToReplace]</param>
        /// <returns></returns>
        public static List<string> GetNodeContentListByNodeName(string pathXMLFile, string nodeName,string valueToReplace, string value)
        {
            List<string> results = new List<string>();
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(pathXMLFile);

                XmlNodeList urlLoc = xmlDoc.GetElementsByTagName(nodeName);

                foreach (XmlNode node in urlLoc)
                {
                    results.Add(node.InnerXml.Replace(valueToReplace, value));
                }
            }
            catch(Exception ex)
            {
                LogToFile.WriteException(ex, "Error parsing the xml DOC : " + pathXMLFile);
            }

            return results;
        }


    }
}
